<template>
  <div class="number-roll-container" :class="`digits-${digits.length}`">
    <div v-for="(digit, index) in digits" :key="index" class="digit-container">
      <div
        v-for="n in 10"
        :key="n - 1"
        class="digit"
        :style="{
          transform: `translateY(-${digit * 100}%)`,
          transition: `${transitionTime}ms ease`,
        }"
      >
        {{ n - 1 }}
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'

const props = defineProps({
  number: {
    type: Number,
    default: 0,
  },
  minDigits: {
    type: Number,
    default: 1,
  },
  transitionTime: {
    type: Number,
    default: 500,
  },
})

const currentNumber = ref(0)

// 将数字转换为数组，例如 75 => ['7', '5']
const digits = computed(() => {
  const numStr = currentNumber.value.toString()
  const numDigits = numStr.length

  // 如果数字位数小于最小位数，且数字不为0，前面补0
  if (numDigits < props.minDigits && currentNumber.value > 0) {
    return [
      ...new Array(props.minDigits - numDigits).fill(0),
      ...numStr.split('').map(Number),
    ]
  }

  // 如果数字为0，只显示一个0
  if (currentNumber.value === 0) {
    return [0]
  }

  return numStr.split('').map(Number)
})

// 监听number属性变化
watch(
  () => props.number,
  (newVal) => {
    // 延迟一点点时间更新，让动画效果更明显
    setTimeout(() => {
      currentNumber.value = newVal
    }, 50)
  },
  { immediate: true }
)
</script>

<style lang="less" scoped>
.number-roll-container {
  display: flex;
  align-items: center;
  justify-content: center;

  .digit-container {
    height: 1em;
    overflow: hidden;
    position: relative;
    width: 0.75em; // 增加宽度到1em
    display: inline-block;

    .digit {
      font-weight: bold;
      height: 1em;
      line-height: 1em;
      text-align: center;
      width: 100%;
    }
  }

  // 针对不同位数调整
  &.digits-3 {
    .digit-container {
      width: 1em; // 3位数时确保足够宽度
    }
  }
}
</style>
